package net.oktaeder.office.view;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Internal representation of mail
 * 
 * @author tuukka
 *
 */
public class Mail {

	private static Log log = LogFactory.getLog(Mail.class);
	
	private String subject;
	private String message;
	private String sender;
	private String recepient;
	private boolean delete;
	
	public Mail() {
		log.trace("Creating instance");
	}
	
	/**
	 * Constructs an internal mail representation from a File
	 * 
	 * @param file File to be used as an input
	 */
	public Mail(File file) {
		//TODO: implement
		FileInputStream fstream;
		DataInputStream in;
		BufferedReader d;
		String text;

		try {
			log.trace("Constructing a mail from a file");
			
			fstream = new FileInputStream(file);
			in = new DataInputStream(fstream);
			d = new BufferedReader(new InputStreamReader(in));
			
			text = d.readLine();
			this.recepient = text;
			text = d.readLine();
			this.subject = text;
			this.sender = "To be filled later";
			text = d.readLine();
			
            while (text != null)
			{
            	if (message == null) {
            		message = text;
            	} else {
            		message = message.concat("\n" + text);
            	}
            	text = d.readLine();
			}
            
			d.close();
			in.close();
			fstream.close();
			
			log.debug("To: " + recepient + "\nSubject: " + subject + "\nMessage: " + message);
			
			delete = false;
			
		} catch (Exception ex) {
			log.error("Failed to create a mail, marking it for deletion", ex);
			delete = true;
		}
	}
	
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getRecepient() {
		return recepient;
	}
	public void setRecepient(String recepient) {
		this.recepient = recepient;
	}
	public String getSender() {
		return sender;
	}
	public void setSender(String sender) {
		this.sender = sender;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public void setDeletion(boolean delete) {
		this.delete = delete;
	}
	public boolean getDeletion() {
		return delete;
	}
}
